// btree.cpp
#include <iostream>
using namespace std;

// 二叉树节点结构体
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

// 二叉树创建函数
TreeNode* CreateBTree(string str) {
    if (str.empty()) {
        return NULL;
    }
    TreeNode* root = NULL;
    stack<TreeNode*> s;
    int i = 0;
    while (i < str.length()) {
        if (str[i] == '(') {
            s.push(new TreeNode(0));
            i++;
        } else if (str[i] == ')') {
            TreeNode* p = s.top();
            s.pop();
            if (p->val == 0) {
                p->val = i + 1;
            } else {
                p->right = new TreeNode(i + 1);
            }
            i++;
        } else if (isdigit(str[i])) {
            TreeNode* p = s.top();
            s.pop();
            p->val = str[i] - '0';
            if (p->val == 0) {
                p->left = new TreeNode(i);
            } else {
                p->right = new TreeNode(i);
            }
            i++;
        }
    }
    return root;
}

// 二叉树输出函数
void PrintBTree(TreeNode* root) {
    if (root == NULL) {
        return;
    }
    cout << root->val << " ";
    PrintBTree(root->left);
    PrintBTree(root->right);
}

// 二叉树查找函数
TreeNode* SearchBTree(TreeNode* root, int val) {
    if (root == NULL) {
        return NULL;
    }
    if (root->val == val) {
        return root;
    } else if (val < root->val) {
        return SearchBTree(root->left, val);
    } else {
        return SearchBTree(root->right, val);
    }
}

// 二叉树高度计算函数
int CalculateBTreeHeight(TreeNode* root) {
    if (root == NULL) {
        return 0;
    }
    int leftHeight = CalculateBTreeHeight(root->left);
    int rightHeight = CalculateBTreeHeight(root->right);
    return max(leftHeight, rightHeight) + 1;
}

// 二叉树释放函数
void ReleaseBTree(TreeNode* root) {
    if (root == NULL) {
        return;
    }
    ReleaseBTree(root->left);
    ReleaseBTree(root->right);
    delete root;
}

// exp7-1.cpp
#include <iostream>
#include "btree.cpp"

int main() {
    string str = "A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))";
    TreeNode* root = CreateBTree(str);
    cout << "二叉树创建成功!" << endl;
    cout << "二叉树输出: ";
    PrintBTree(root);
    cout << endl;
    TreeNode* hNode = SearchBTree(root, 'H');
    if (hNode != NULL) {
        cout << "H 结点的左孩子结点值: " << hNode->left->val << endl;
        cout << "H 结点的右孩子结点值: " << hNode->right->val << endl;
    } else {
        cout << "未找到 H 结点!" << endl;
    }
    cout << "二叉树高度: " << CalculateBTreeHeight(root) << endl;
    ReleaseBTree(root);
    return 0;
}
